/**
 * 
 */
package info.niwota.group;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.Contacts;
import android.provider.Contacts.ContactMethods;
import android.provider.Contacts.ContactMethodsColumns;
import android.provider.Contacts.People;
import android.provider.Contacts.PeopleColumns;
import android.text.TextUtils;

/**
 * @author qiangli
 * 
 */

public class ContactAdapter1 extends ContactAdapter {

	public ContactAdapter1() {
	}

	@Override
	public Intent getIntent() {
		return (new Intent(Intent.ACTION_PICK, People.CONTENT_URI));
	}

	@Override
	protected void loadContactsInConact(Context context, Set<EmailContact> contacts) {
		//
		Uri uri = Contacts.ContactMethods.CONTENT_URI;
		String[] proj = new String[] { ContactMethods.PERSON_ID,
				PeopleColumns.DISPLAY_NAME, PeopleColumns.STARRED,
				PeopleColumns.LAST_TIME_CONTACTED,
				PeopleColumns.TIMES_CONTACTED, ContactMethodsColumns.KIND,
				ContactMethodsColumns.DATA };
		String by = PeopleColumns.DISPLAY_NAME + " ASC, "
				+ ContactMethodsColumns.DATA + " ASC ";
		String sel = ContactMethodsColumns.KIND + " in (1, 3)"; // email and im

		ContentResolver cr = context.getContentResolver();
		Cursor c = cr.query(uri, proj, sel, null, by);
		//
		if (c == null) {
			return;
		}
		try {
			if (!c.moveToFirst()) {
				return;
			}
			//
			int colId = c.getColumnIndex(ContactMethods.PERSON_ID);
			int colName = c.getColumnIndex(PeopleColumns.DISPLAY_NAME);
			int colStar = c.getColumnIndex(PeopleColumns.STARRED);
			int colEmail = c.getColumnIndex(ContactMethodsColumns.DATA);
			int colLastTime = c
					.getColumnIndex(PeopleColumns.LAST_TIME_CONTACTED);
			int colTimes = c.getColumnIndex(PeopleColumns.TIMES_CONTACTED);
			String prev = "";
			EmailContact ec = null;
			ArrayList<String> el = new ArrayList<String>(); // emails
			do {
				String n = c.getString(colName);
				if (n.equals(prev)) {
					String s = c.getString(colEmail);
					//
					if (!el.contains(s)) {
						el.add(s);
					}
				} else {
					// new entry
					if (ec != null) {
						ec.emails = el.toArray(new String[0]);
						contacts.add(ec);
					}
					//
					ec = new EmailContact();
					el.clear();
					prev = n;
					//
					ec.id = c.getLong(colId);
					ec.name = n;
					ec.starred = c.getInt(colStar);
					ec.lastTime = c.getLong(colLastTime);
					ec.times = c.getInt(colTimes);
					//
					String s = c.getString(colEmail);
					el.add(s);
				}
			} while (c.moveToNext());
			if (ec != null) {
				ec.emails = el.toArray(new String[0]);
				contacts.add(ec);
			}
		} finally {
			c.close();
		}
		//
	}

	@Override
	protected void loadAddressesInConact(Context ctx, Set<EmailAddress> addresses) {
		//
		Uri uri = Contacts.ContactMethods.CONTENT_URI;
		String[] proj = new String[] { ContactMethods._ID,
				PeopleColumns.DISPLAY_NAME, ContactMethodsColumns.KIND,
				ContactMethodsColumns.DATA };
		// sort by id so that we always
		// get display name the first time it is used for the email
		// usually it is the regular name instead of the list name
		String by = ContactMethods._ID + " ASC ";
		String sel = ContactMethodsColumns.KIND + " in (1, 3)"; // email and im
		ContentResolver cr = ctx.getContentResolver();
		Cursor c = cr.query(uri, proj, sel, null, by);
		//
		if (c == null) {
			return;
		}
		try {
			if (!c.moveToFirst()) {
				return;
			}
			//
			int colName = c.getColumnIndex(PeopleColumns.DISPLAY_NAME);
			int colEmail = c.getColumnIndex(ContactMethodsColumns.DATA);
			//
			Set<EmailAddress> al = new HashSet<EmailAddress>();
			do {
				String a = c.getString(colEmail);
				String n = c.getString(colName);
				try {
					EmailAddress ia = new EmailAddress(a, n);
					al.add(ia);
				} catch (Exception e) {
					// e.printStackTrace();
				}
			} while (c.moveToNext());
			addresses.addAll(al);
		} finally {
			c.close();
		}
		//
	}

	@Override
	public void saveAsContact(Context ctx, String name, int star, String[] emails) {
		ContentResolver cr = ctx.getContentResolver();
		ContentValues v = new ContentValues();
		//
		if (name == null) {
			return;
		}
		v.put(People.NAME, name);
		// 1 = the new contact is added to favorites
		// 0 = the new contact is not added to favorites
		star = (star == 0 ? 0 : 1);
		v.put(People.STARRED, star);
		Uri uri = cr.insert(People.CONTENT_URI, v);
		//
		if (emails == null || emails.length == 0) {
			return;
		}
		Uri emailUri = Uri.withAppendedPath(uri,
				People.ContactMethods.CONTENT_DIRECTORY);
		// Log.d(TAG, "addMailList email Uri: " + emailUri + emails.length);
		//
		v.clear();
		//
		for (int i = 0; i < emails.length; i++) {
			v.put(People.ContactMethods.KIND, Contacts.KIND_EMAIL);
			v.put(People.ContactMethods.DATA, emails[i]);
			v.put(People.ContactMethods.TYPE, People.ContactMethods.TYPE_OTHER);
			//
			cr.insert(emailUri, v);
		}
	}

	@Override
	protected void loadGroupNamesInConact(Context ctx, Set<String> names) {
//		String[] proj = new String[] { android.provider.BaseColumns._ID,
//				PeopleColumns.DISPLAY_NAME };
//		ContentResolver cr = context.getContentResolver();
//		Cursor c = cr.query(Contacts.People.CONTENT_URI, proj,
//				PeopleColumns.DISPLAY_NAME + " like ?", new String[] { "@%" },
//				PeopleColumns.DISPLAY_NAME + " ASC");
//		//
		
		Uri uri = Contacts.ContactMethods.CONTENT_URI;
		String[] proj = new String[] { ContactMethods._ID,
				PeopleColumns.DISPLAY_NAME, ContactMethodsColumns.KIND,
				ContactMethodsColumns.DATA };
		String by = PeopleColumns.DISPLAY_NAME + " ASC";
		String sel = PeopleColumns.DISPLAY_NAME + " like ? AND " + ContactMethodsColumns.KIND + " in (1, 3)"; // email and im
		String[] args = new String[] { "@%" };
		ContentResolver cr = ctx.getContentResolver();
		Cursor c = cr.query(uri, proj, sel, args, by);
		if (c == null) {
			return;
		}
		try {
			if (!c.moveToFirst()) {
				return;
			}
			int colName = c.getColumnIndex(People.DISPLAY_NAME);
			int colEmail = c.getColumnIndex(ContactMethodsColumns.DATA);
			do {
				String a = c.getString(colEmail);
				if (TextUtils.isEmpty(a)) {
					continue;
				}
				String n = c.getString(colName);
				names.add(n);
			} while (c.moveToNext());
		} finally {
			c.close();
		}
	}

	@Override
	protected Bitmap loadContactPhoto(Context context, long id, int res) {
		Uri uri = ContentUris.withAppendedId(People.CONTENT_URI, id);
		Bitmap bm = People.loadContactPhoto(context, uri, res, null);
		return bm;
	}

	@Override
	protected void addEmailToContact(Context context, long id, String[] emails) {
		Uri uri = ContentUris.withAppendedId(People.CONTENT_URI, id);
		Uri emailUri = Uri.withAppendedPath(uri,
				People.ContactMethods.CONTENT_DIRECTORY);
		ContentValues v = new ContentValues();
		ContentResolver cr = context.getContentResolver();
		for (int i = 0; i < emails.length; i++) {
			v.put(People.ContactMethods.KIND, Contacts.KIND_EMAIL);
			v.put(People.ContactMethods.DATA, emails[i]);
			v.put(People.ContactMethods.TYPE, People.ContactMethods.TYPE_OTHER);
			cr.insert(emailUri, v);
		}
	}

	@Override
	protected boolean hasEmailInContact(Context context, String email) {
		Uri uri = Contacts.ContactMethods.CONTENT_URI;
		String[] proj = new String[] { android.provider.BaseColumns._ID,
				PeopleColumns.DISPLAY_NAME, ContactMethodsColumns.DATA };
		String sel = ContactMethodsColumns.DATA + "= ?";
		String[] args = new String[] { email };
		Cursor c = context.getContentResolver().query(uri, proj, sel, args,
				null);
		if (c == null) {
			return false;
		}
		try {
			return (c.moveToFirst());
		} finally {
			c.close();
		}
	}

	@Override
	protected String[] getEmailsInContact(Context ctx, String name) {
		Uri uri = Contacts.ContactMethods.CONTENT_URI;
		String[] proj = new String[] { PeopleColumns.DISPLAY_NAME,
				ContactMethodsColumns.DATA };
		String sel = PeopleColumns.DISPLAY_NAME + "= ?";
		String[] args = new String[] { name };
		Cursor c = ctx.getContentResolver().query(uri, proj, sel, args,
				null);
		if (c == null) {
			return null;
		}
		try {
			if (!c.moveToFirst()) {
				return null;
			}
			//
			int colEmail = c.getColumnIndex(ContactMethodsColumns.DATA);
			Set<String> set = new HashSet<String>();
			do {
				String s = c.getString(colEmail);
				set.add(s);
			} while (c.moveToNext());
			return set.toArray(new String[0]);
		} finally {
			c.close();
		}
	}

	@Override
	protected long getContactId(Context context, String name) {
		String[] proj = new String[] { People._ID, PeopleColumns.DISPLAY_NAME, };
		Cursor c = context.getContentResolver().query(People.CONTENT_URI, proj,
				PeopleColumns.DISPLAY_NAME + " = ?", new String[] { name },
				null);
		if (c == null) {
			return -1;
		}
		try {
			if (!c.moveToFirst()) {
				return -1;
			}
			// return the first one found, assuming name is unique
			int idCol = c.getColumnIndex(People._ID);
			return c.getLong(idCol);
		} finally {
			c.close();
		}
	}
}
